//
//  HMStadusViewModel.swift
//  微博
//
//  Created by 程双岐 on 16/9/23.
//  Copyright © 2016年 heima. All rights reserved.
//

import UIKit

//微博首页的cell

class HMStadusViewModel: NSObject {
    
    var status: HMStatus?
    
    var mbrankimage : UIImage?
    
    var repostsCountContent: String?
    
    var commentsCountContent: String?
    
    var attitudesCountContent: String?
    
    var retweetContent: String?
    
    var verifiedTypeImage: UIImage?
    
    var sourceContent: String?
    
    
    /*
     
      时间判断逻辑
      是否是今年
          是否是今天
              是否是一分钟之前
                刚刚
              是否是一小时之前
                xx小时前
     
     
          是否是昨天
     
          其他
            11-21  11：11
       不是今年
          2015-10-21 10：10
     
     
     */
    var timeContent: String?{
        
        guard let createAt = status?.created_at else {
            return nil
        }
        
//        let createDate = Date.sinaDate(createAt: createAt)
        
        let dt = DateFormatter()
        
        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        dt.locale = Locale(identifier: "en_US")
        
        let createAtDate = dt.date(from: createAt)!
        
        
        if isThisyear(createAtDate: createAtDate) {
            
            let currentCalendar = Calendar.current
            if currentCalendar.isDateInToday(createAtDate) {
                
                let timeinterVal = abs(createAtDate.timeIntervalSinceNow)
                if timeinterVal < 60 {
                    return "刚刚"
                }else if timeinterVal < 3600{
                    let result = timeinterVal / 60
                    return "\(Int(result))分钟前"
                }else{
                    let result = timeinterVal / 3600
                    return "\(Int(result))小时前"
                }
                
            }else if currentCalendar.isDateInYesterday(createAtDate){
                dt.dateFormat = "昨天 HH:mm"
            }else{
                dt.dateFormat = "MM-dd HH:mm"
            }
            
        }else{
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        
        
        
        return dt.string(from: createAtDate)
    }
    
    var originalAttributedString: NSAttributedString?
    var retweetAttruvutedString: NSAttributedString?
    
    init(status: HMStatus) {
        super.init()
        self.status = status
        handleMBrankimage(mbrank: status.user?.mbrank ?? 0)
        repostsCountContent = handleCountContent(count: status.reposts_count, defaultTitle: "转发")
        commentsCountContent = handleCountContent(count: status.comments_count, defaultTitle: "评论")
        attitudesCountContent = handleCountContent(count: status.attitudes_count, defaultTitle: "赞")
        handleRetweetContent(status: status)
        handleVerfiedTypeImage(verifiedType: status.user?.verified_type ?? 0)
        handleSourceContent(source: status.source ?? "")
        originalAttributedString = handleStatusAttrbutdeString(status: status.text!)
    }
    
    //判断年
    private func isThisyear(createAtDate: Date) -> Bool{
        let dt = DateFormatter()
        dt.dateFormat = "yyyy"
        
        dt.locale = Locale(identifier: "en_US")
        
        let createAtYear = dt.string(from: createAtDate)
        
        let currentDateYear = dt.string(from: Date())
        
        return createAtYear == currentDateYear
    }
    
    private func handleStatusAttrbutdeString(status: String) -> NSAttributedString {
        
        let resultAttributedString = NSMutableAttributedString(string: status)
        
        let matchResult = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: []).matches(in: status, options: [], range: NSMakeRange(0, (status as NSString).length))
        
        for match in matchResult.reversed() {
            let range = match.range
            let chs = (status as NSString).substring(with: range)
            //通过表情描述查找模型
            if let emoticon = HMEmoticonTools.shareTools.selectedEmoticonarray(chs: chs) {
                //                let image = UIImage(named: emoticon.path!)
                //根据表情模型里面图片路劲穿件对应的富文本
                let attrbutedStr = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: UIFont.systemFont(ofSize: 14))
                
                //根据指定范围替换成富文本
                resultAttributedString.replaceCharacters(in: range, with: attrbutedStr)
            }
            
            
        }
        resultAttributedString.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, resultAttributedString.length))
        
        return resultAttributedString
    }
    
    
    private func handleSourceContent(source: String){
        
        //判断其字符串是否包含特定的字符串
        if source.contains("\">") && source.contains("</"){
            
            let startRange = source.range(of: "\">")!
            let endRange = source.range(of: "</")!
            
            //光标的上限索引
            let startIndex = startRange.upperBound
            //光标的下限索引
            let endIndex = endRange.lowerBound
            
            sourceContent = "来源: " + source.substring(with: startIndex..<endIndex)
        }
        
    }
    
    
    
    private func handleVerfiedTypeImage(verifiedType: Int){
        
        switch verifiedType {
        case 1:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")
        default:
            break
        }
        
        
    }
    
    private func handleCountContent(count: Int,defaultTitle: String)-> String{
        if count > 0{
            return "\(count)"
        }else{
            return defaultTitle
        }
    }
    
    private func handleMBrankimage(mbrank: Int){
        if mbrank >= 1 && mbrank <= 6 {
            mbrankimage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        
    }
    
    private func handleRetweetContent(status:HMStatus){
        if status.retweeted_status != nil {
            let name = status.retweeted_status?.user?.screen_name
            let content = status.retweeted_status?.text
            
            if name != nil && content != nil {
                retweetContent = "@\(name!): \(content!)"
            }
            
            retweetAttruvutedString = handleStatusAttrbutdeString(status: retweetContent!)
        }
    }

}






